package com.cooper.controllers.trade;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.cooper.controllers.LoginRequired;
import com.cooper.core.JsonResult;
import com.cooper.domain.OrderEntry;
import com.cooper.entity.OrderItem;
import com.cooper.entity.UserInfo;
import com.cooper.service.trade.OrderService;
import com.cooper.util.Controllers;
import com.cooper.util.StringUtils;
import com.cooper.vo.OrderCreateVo;
import com.cooper.vo.SendAddressVo;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

/**
 * 订单处理
* @Description: 
* @version: v1.0.0
* @author: tianlg
* @date: Mar 8, 2015 11:44:14 AM
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* Mar 8, 2015      tianlg          v1.0.0
 */
@LoginRequired
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	@Post("create")
	public Object create(Invocation inv, OrderCreateVo createVo){
		JsonResult json = new JsonResult();
		String strOrderItems = inv.getParameter("orderItems");
		String strAddressVo = inv.getParameter("strAddressVo");
		if(StringUtils.isEmpty(strOrderItems)){
			json.setMessage("PLEASE SELECT ITEMS FIRST! ");
		} else {
			try{
				UserInfo userInfo = Controllers.getUserInfo(inv);
				SendAddressVo addressVo = JSON.parseObject(strAddressVo, SendAddressVo.class);
				List<OrderItem> orderItems = JSON.parseArray(strOrderItems, OrderItem.class);
				json = this.orderService.validateSaveOrderParam(userInfo, createVo, orderItems);
				if(true == json.isSuccess()){
					OrderEntry entry = this.orderService.makeOrderEntry(userInfo, addressVo, createVo, orderItems);
					this.orderService.saveOrder(entry, userInfo, addressVo);
					json.setSuccess(true);
					json.setMessage(entry.getOrderNum());
				}
			} catch(Exception e){
				json.setMessage(e.getMessage());
				e.printStackTrace();
			}
		}
		return json;
	}
	
	@Get("tip/{orderNum:[0-9]+}")
	public String showTip(Invocation inv, @Param("orderNum") String orderNum) throws Exception{
		inv.addModel("orderInfo", this.orderService.getOrderInfo(orderNum));
		return "OrderTip";
	}
	
	@Get("detail/{orderNum:[0-9]+}")
	public String detail(Invocation inv, @Param("orderNum") String orderNum){
		
		return "OrderDetail";
	}
}
